package com.ternnetwork.core.access.controller;

import java.security.Principal;

import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.ternnetwork.commons.model.http.BaseResponse;
import com.ternnetwork.commons.utils.JsonUtils;
import com.ternnetwork.core.accesscontroll.entity.Resources;
import com.ternnetwork.core.accesscontroll.enums.ResourcesType;
import com.ternnetwork.core.accesscontroll.service.ResourcesService;



@Controller
@RequestMapping("/access/resources/*")
public class ResourcesController {
	

	 private final ResourcesService resourcesService;


	public ResourcesController(ResourcesService resourcesService) {
		this.resourcesService = resourcesService;
	}

	@PreAuthorize("hasAnyAuthority('ACCESS_RESOURCES_ADD')")
	 @RequestMapping("/add")
	 @CacheEvict(value="userMenu", allEntries=true)
     public @ResponseBody BaseResponse add(String requestJson)  throws Exception{
       	 BaseResponse baseResponse=new BaseResponse();
    	 Resources t=JsonUtils.jsonToObjectThrowsException(requestJson, Resources.class);
		 baseResponse=resourcesService.add(t);
		 return baseResponse;
    }

	 @PreAuthorize("hasAnyAuthority('ACCESS_RESOURCES_UPDATE')")
	 @RequestMapping("/update")
	 //清空用户菜单缓存
	 @CacheEvict(value="userMenu", allEntries=true)
     public @ResponseBody BaseResponse update(String requestJson)  throws Exception{
       	 BaseResponse baseResponse=new BaseResponse();
    	 Resources t=JsonUtils.jsonToObjectThrowsException(requestJson, Resources.class);
		 baseResponse=resourcesService.update(t);
		 return baseResponse;
     }


	 @PreAuthorize("hasAnyAuthority('ACCESS_RESOURCES_DELETE')")
	 @RequestMapping("/deleteById")
	 @CacheEvict(value="userMenu", allEntries=true)
     public @ResponseBody BaseResponse deleteById(Long id) {
    	 return resourcesService.deleteById(id);
     }
	 
	 @RequestMapping("/getZtreeJson")
     public @ResponseBody BaseResponse getZtreeJson(ResourcesType  resourcesType) {
    	 return resourcesService.getZtreeJson(resourcesType);
     }
	 
	 @RequestMapping("/getAllWithCheckBoxZtreeJson")
     public @ResponseBody BaseResponse getAllWithCheckBoxZtreeJson(ResourcesType  resourcesType,Long roleId) {
    	 return resourcesService.getAllWithCheckBoxZtreeJson(resourcesType,roleId);
     }
	 
	 /**
	  * 获取已登录用户对应的菜单
	  * @param user
	  * @return
	  */
	 @RequestMapping("/getUserMenuZtreeJson")
	 //如果当前用户的菜单在缓存中已经存在，则需从缓存中取，而不是重新在数据库中获取
	 @Cacheable(value="userMenu",key="#user.name")
     public @ResponseBody BaseResponse getUserMenuZtreeJson(Principal user) {
    	 return resourcesService.getZtreeJson(ResourcesType.MENU,user.getName());
     }
	 
	
	
	

}
